package com.wuye.interceptor;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.logging.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLEncoder;
import java.util.*;
import java.io.*;
import com.wuye.web.*;

public class LogonInterceptor implements HandlerInterceptor{
	private Log log=LogFactory.getLog(this.getClass());

	private String loginUrl="/user/login.jspx";
	private String adminLoginUrl="/admin/login.jspx";

	private String[] publicUrl={"/home","/user/login.jspx","/loginAction.jspx","/admin/login.jspx","/admin/loginAction.jspx"};
	private String adminPrefix="/admin/";

	private String timeAttribName="startTime";

	@Autowired
	private SessionHandler sessionHandler;

	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler){
		request.setAttribute(timeAttribName,new Long(System.currentTimeMillis()));
		String path=request.getServletPath();
		log.info("begin of "+path);
		for(String i : publicUrl){
			if(i.equals(path)){
				log.info("---public access");
				return true;
			}
		}
		//---Check admin session
		if(path.startsWith(adminPrefix)){
			if(sessionHandler.adminSessionExists(request.getSession())){
				log.info("---admin already login");
				return true;
			}
			log.info("---require admin login");
			try{
				response.sendRedirect(adminLoginUrl);
			}catch(IOException e){}
			return true;
		}
		if(sessionHandler.useSessionExists(request.getSession())){
			log.info("---already login");
			return true;
		}
		log.info("---require login");
		try{
			String uri = request.getRequestURI()+(null!=request.getQueryString()?("?"+request.getQueryString()):"");
			uri = URLEncoder.encode(uri, "UTF-8");
			response.sendRedirect(loginUrl+"?uri="+uri);
		}catch(IOException e){}
		return true;
	}

	public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView){
		Long when=(Long)request.getAttribute(timeAttribName);
		long tStart=when.longValue();
		long tEnd=System.currentTimeMillis();
		long tGap=tEnd-tStart;
		log.info("end of "+request.getServletPath()+"---execute time:"+String.valueOf(tGap));
	}

	public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex){
	}
}